package com.lagou.handler;

import com.lagou.service.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.util.concurrent.Callable;

/**
 * 自定义事件处理器
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    //1.定义成员变量
    private ChannelHandlerContext context;

    private String result;//记录服务器返回的数据


    private RpcRequest rpcRequest;

    //2.实现channelActive 客户端和服务器连接时该方法就自动执行


    /**
     * 心跳空闲次数
     */
    private int idle_count = 1;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //初始化context
        this.context = ctx;
    }
    /**
     * 心跳超时事件
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {

        if (obj instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) obj;
            if (IdleState.READER_IDLE.equals(event.state())) {
                if (idle_count > 2) {
                    ctx.close();
                }
                idle_count++;
            } else {
                idle_count = 1;
            }
        } else {
            super.userEventTriggered(ctx, obj);
        }
    }

    //3.事故下班channelRead 放我们读到服务器数据，该方法自动执行


    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //将读到的服务器的数据msg，设置为成员变量的值
        result = msg.toString();
        notify();
    }

    //4.将客户端的数据写到服务器
    public synchronized Object call() throws Exception {
        //context给服务器写数据
        context.writeAndFlush(rpcRequest);
        wait();
        return result;
    }

    public void setRpcRequest(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }
}
